package com.authenticateCenter.domain.entity;

import java.io.Serializable;
import java.util.List;

import com.authenticateCenter.domain.Checker;
import com.authenticateCenter.mapper.UserMapper;
import com.authenticateCenter.mapper.UserRoleMapper;
import com.authenticateCenter.service.IUserService;
import com.authenticateCenter.util.MybatisUtil;
import com.authenticateCenter.util.StringUtil;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.*;
import org.springframework.util.Assert;

/**
 * <p>
 * 
 * </p>
 *
 * @author 大忽悠
 * @since 2022年10月08日
 */
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable, Checker<User> {

    private static final long serialVersionUID = 1L;
    /**
     * 用户不设置密码,默认给予此值
     */
    private static final String NONE_PWD="NONE_PWD";

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String username;

    private String password;

    private Integer enabled;

    private Integer accountNonExpired;

    private Integer accountNonLocked;

    private Integer credentialsNonExpired;

    public static void existCheckWithEx(Integer uid, UserMapper userMapper) {
        User user = userMapper.selectById(uid);
        Assert.notNull(user,"id="+uid+"的用户不存在");
    }
    /**
     * 是否重复发放角色
     * @param uid
     * @param roleIdList
     */
    public static void repeatReleaseCheck(Integer uid, List<Integer> roleIdList, UserRoleMapper userRoleMapper) {
        boolean exists = userRoleMapper.exists(new QueryWrapper<UserRole>()
                .eq("uid", uid)
                .in("rid", roleIdList));
        if(exists){
            throw new IllegalArgumentException("当前用户已经具备角色列表"+roleIdList+"中某个角色,请重新检查后再赋权");
        }
    }

    public static Boolean existCheckWithoutEx(String name, UserMapper userMapper) {
           return userMapper.selectOne(new QueryWrapper<User>().eq("username",name))!=null;
    }


    /**
     * 1. 用户名是否重复
     * 2. 密码是否设置,如果没有设置,那么默认 NONE_PWD
     * @param iUserService
     */
    @Override
    public void insertCheck(IService<User> iService) {
        MybatisUtil.repeatCheck(iService,"username",username,"用户名重复");
        if(StringUtil.isNullOrEmpty(password)){
            password=NONE_PWD;
        }
    }

}
